# coding: utf-8
import random, datetime

from flask_login import login_user, current_user,logout_user,login_required
from models.models import User
from .. import db, mail, redis_cache
from . import auth
from .forms import Login_form, register_form,password_form
from flask import render_template, redirect,url_for, flash, request, make_response
from flask_mail import Message
from functools import wraps

def login_by_cookie(f):
    @wraps(f)
    def decode_cookie(*args,**kwargs):
        if current_user:
            return f(*args,**kwargs)
        login_cookie = request.cookies.get('auto_login')
        if login_cookie:
            user_id = login_cookie
            login_user(user_id)
        return f(*args,**kwargs)
    return decode_cookie

@auth.route('/login', methods=['GET', 'POST'])
@login_by_cookie
def login():
    if current_user.is_authenticated:
        return redirect(url_for('blog.home'))
    form = Login_form()
    operation = '注册'
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.name.data).first()
        if user is not None and user.password_hash == form.password.data:
            login_user(user)
            resp = make_response(redirect(url_for('blog.home')))
            resp.set_cookie(key='auto_login',value=str(user.id),max_age=7*24*3600,domain='0.0.0.0')
            return resp
        flash('Invalid username or password', 'waring')
    return render_template('login.html', form=form, operation=operation)


@auth.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('blog.home'))
    form = register_form()
    operation = '登陆'
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None:
            flash('user is already exit')
        cache = redis_cache.get(form.email.data+'_cache').decode('utf-8')
        a=form.cache.data.lower() != cache.lower()
        if cache is None or form.cache.data.lower()!=cache.lower():
            flash('验证码输入错误')
        else:
            new_user = User(username=form.name.data, email=form.email.data,
                            password_hash=form.password.data)
            db.session.add(new_user)
            db.session.commit()
            flash('create new user success')
            redis_cache.delete(form.email.data+'_cache')
            return redirect(url_for('auth.login'))
    return render_template('login.html', form=form, operation=operation)

@auth.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.login'))

@auth.route('/change_pwd',methods=['GET','POST'])
@login_required
def change_password():
    form = password_form()
    user = current_user
    if form.validate_on_submit():
        if user.password_hash!=form.old_pwd.data:
            flash('输入的密码错误')
        elif form.re_pwd.data!=form.new_pwd.data:
            flash('两次输入的密码不一致')
        else:
            user.password_hash = form.new_pwd.data
            db.session.commit()
            flash('修改密码成功，请重新登陆')
            return redirect(url_for('auth.logout'))
    return render_template('change_pwd.html',form=form)

@auth.route('/send_cache',methods=['POST'])
def send_cache():
    email = request.form.get('email')
    s = 'abcdefghijklmnopqrstuvwxyz1234567890'
    cache = ''
    for i in range(6):
        cache+=random.choice(s)
    message = Message(subject='验证码',recipients=[email],body=cache)
    email_cache = email+'_cache'
    redis_cache.set(email_cache,cache)
    redis_cache.expireat(email_cache,datetime.datetime.now()+datetime.timedelta(seconds=60))
    mail.send(message)
    return jsonify({'data':True})